/**
 * @Description:登录主入口
 * @author 云离
 * @date: 2018/12/28
 */
import React, { Component } from "react";
import qs from "qs";
import md5 from "md5-node";
import { actions } from "../../../../reducers/main";
import { connect } from "react-redux";
import { withRouter } from "react-router-dom";
import {
  message,
  Spin,
  Table,
  Switch,
  Button,
  Icon,
  Pagination,
  Modal,
  Input,
  Popover
} from "antd";
import MyForm from "../../../components/Form";
import axios from "../../../../apis/api";
import AddUserForm from "../../charts/businessSummary/addUserForm";
import UserForm from "./addUserForm";
import EditGroupUser from "./editGroupUser";

const { confirm } = Modal;

const mapStateToProps = (state, ownProps) => {
  return {
    vwAgentCashStat: state.main.vwAgentCashStat,
    vwAgentCashDayStat: state.main.vwAgentCashDayStat,
    isAdmin: state.main.isAdmin,
    isGroup: state.main.isGroup
  };
};

const mapDispatchToProps = dispatch => {
  return {
    fetchInitData: next => dispatch(actions.fetchInitData(next))
  };
};

const formItems = [
  {
    label: "归属部门",
    key: "deptId",
    type: "select",
    options: [
      {
        label: "所有",
        value: ""
      },
      {
        label: "管理员",
        value: "101"
      },
      {
        label: "业务员",
        value: "123"
      }
    ]
  },
  {
    label: "登录名称",
    key: "loginName",
    type: "input"
  },
  {
    label: "商户编号",
    key: "params[userId]",
    type: "input"
  },
  {
    label: "用户状态",
    key: "status",
    type: "select",
    options: [
      {
        label: "所有",
        value: ""
      },
      {
        label: "正常",
        value: "0"
      },
      {
        label: "停用",
        value: "1"
      }
    ]
  },
  {
    label: "创建开始时间",
    key: "params[beginTime]",
    type: "DatePicker"
  },
  {
    label: "创建结束时间",
    key: "params[endTime]",
    type: "DatePicker"
  },
  {
    label: "用户名称",
    key: "userName",
    type: "input"
  }
];

class UserMng extends Component {
  state = {
    initForm: {
      deptId: "",
      loginName: "",
      "params[userId]": "",
      status: "",
      "params[beginTime]": null,
      "params[endTime]": null,
      userName: ""
    },
    formItmes: formItems,
    searchParam: {},
    loading: false,
    depMap: {},
    pageSize: 10,
    curPage: 1,
    tableData: {
      total: 0,
      rows: []
    },
    pauseOrderVisible: false,
    curSelData: {},
    scoreVisible: false,
    scoreValue: 0,
    addressVisible: false,
    addressValue: 0,
    salesmanInScore: 0,
    salesmanOutScore: 0,
    resetVisible: false,
    resetValue: 0,
    initCardForm: {},
    visibleDlg: false,
    visibleGroupDlg: false,
    groupUserList: {},
    cardFormTitle: "",
    cardFormType: "add",
    payVisible: false,
    payValue: "",
    pwdVisible: false,
    pwdValue: "",
    userDlg: false // 添加管理员 和 添加业务员 是否可见
  };

  addUser = () => {
    this.setState({
      visibleDlg: true,
      initCardForm: {},
      cardFormType: "add",
      cardFormTitle: "添加会员"
    });
  };

  addAdmin = () => {
    this.setState({
      userDlg: true,
      initCardForm: { roleIds: 102, deptId: 101 },
      cardFormType: "add",
      cardFormTitle: "添加管理员"
    });
  };
  addGroup = () => {
    this.setState({
      userDlg: true,
      initCardForm: { roleIds: 109, deptId: 101 },
      cardFormType: "add",
      cardFormTitle: "添加组长"
    });
  };
  editGroupUser = () => {
    this.setState({
      visibleGroupDlg: true,
      initCardForm: { roleIds: 109, deptId: 101 },
      cardFormType: "add",
      cardFormTitle: "添加组长"
    });
  };
  // 添加业务员
  addSalesman = () => {
    this.setState({
      userDlg: true,
      initCardForm: { roleIds: 107, deptId: 123 },
      cardFormType: "add",
      cardFormTitle: "添加业务员"
    });
  };
  // editUser = async card => {
  //   const result = await axios.get("/channel/businessInfo/" + card.userId);
  //   this.setState({
  //     visibleDlg: true,
  //     cardFormType: "edit",
  //     initCardForm: { ...card, invitationCode: result.data.invitationCode },
  //     cardFormTitle: "修改会员"
  //   });
  // };
  handleSearch = value => {
    this.setState(
      {
        curPage: 1,
        searchParam: value
      },
      this.searchTable
    );
  };

  componentDidMount() {
    this.init();
    this.getSalesman();
    this.getHost();
  }

  handleSearch = value => {
    this.setState(
      {
        curPage: 1,
        searchParam: value
      },
      this.searchTable
    );
  };

  updatePayPwd = async () => {
    const { payValue } = this.state;
    try {
      const result = await axios.post(
        "/channel/businessInfo/resetPayPwd",
        qs.stringify({
          id: this.state.curSelData.userId,
          password: md5(payValue)
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }

    this.setState({ payVisible: false });
  };

  updateUserPwd = async () => {
    const { pwdValue } = this.state;
    try {
      const result = await axios.post(
        "/system/user/resetPwd",
        qs.stringify({
          userId: this.state.curSelData.userId,
          password: md5(pwdValue)
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }
    this.setState({ pwdVisible: false });
  };

  componentDidMount() {
    this.init();
  }

  init = async () => {
    try {
      this.setState({
        loading: true
      });
      // const result = await axios.get("/system/dept/treeData");
      // const map = {};
      // const newItems = JSON.parse(JSON.stringify(formItems));
      // result.forEach(item => {
      //   map[item.id] = item;
      //   newItems[0].options.push({
      //     label: item.title,
      //     value: item.id
      //   });
      // });
      this.searchTable();
      this.setState({
        // depMap: map,
        // formItmes: newItems,
        loading: false
      });
    } catch (e) {
      this.setState({
        loading: false
      });
      message.error(e.message);
    }
  };

  searchTable = async () => {
    const { pageSize, curPage, searchParam, depMap } = this.state;
    const query = {
      orderByColumn: "createTime",
      isAsc: "desc",
      pageSize,
      pageNum: curPage,
      deptId: searchParam.deptId,
      loginName: searchParam.loginName,
      "params[userId]": (searchParam.params && searchParam.params.userId) || "",
      "params[deptId]": "101,123",
      status: searchParam.status,
      "params[beginTime]":
        (searchParam.params &&
          searchParam.params.beginTime &&
          searchParam.params.beginTime.format("YYYY-MM-DD")) ||
        "",
      "params[endTime]":
        (searchParam.params &&
          searchParam.params.endTime &&
          searchParam.params.endTime.format("YYYY-MM-DD")) ||
        "",
      userName: searchParam.userName,
      parentId:
        (searchParam.deptId &&
          depMap[searchParam.deptId] &&
          depMap[searchParam.deptId].pId) ||
        ""
    };
    try {
      this.setState({
        loading: true
      });
      const result = await axios.post("/system/user/list", qs.stringify(query));
      console.log(result);
      if (result.code === 0) {
        this.setState({
          tableData: result,
          loading: false
        });
      } else {
        this.setState({
          loading: false
        });
        message.error(result.msg);
      }
    } catch (e) {
      this.setState({
        loading: false
      });
      message.error(e.message);
    }
  };
  // 用户状态改变
  handleUserStateChange = data => {
    confirm({
      title: "系统提示",
      content:
        data.status === "0" ? "确认要停用该用户吗？" : "确认要启用该用户吗？",
      okText: "确认",
      cancelText: "取消",
      onOk: async () => {
        try {
          const result = await axios.post(
            "/system/user/changeStatus",
            qs.stringify({
              userId: data.userId,
              status: data.status === "0" ? 1 : 0
            })
          );
          if (result.code === 0) {
            message.success(result.msg);
            this.searchTable();
          } else {
            message.error(result.msg);
          }
        } catch (e) {
          console.log(e);
          message.error(e.message);
        }
      },
      onCancel() {}
    });
    console.log(data);
  };

  // 删除用户
  delUser = data => {
    Modal.confirm({
      title: "系统提示",
      content: "确定删除该条用户信息吗？",
      okText: "确定",
      cancelText: "取消",
      onOk: async () => {
        await axios.post(
          "/system/user/remove",
          qs.stringify({
            ids: data.userId
          })
        );
        message.success("删除成功");
        this.init();
      }
    });
  };

  setRate = async () => {
    const { scoreValue } = this.state;
    if (scoreValue === 0) {
      message.info("请输入非0的数字！");
      return;
    }
    try {
      const result = await axios.post(
        "/channel/salesmanInfo/addOrUpdate",
        qs.stringify({
          userId: this.state.curSelData.userId,
          rate: this.state.scoreValue
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }
    this.setState({ scoreVisible: false });
  };

  setAddress = async () => {
    try {
      const result = await axios.post(
        "/channel/salesmanInfo/updateAddress",
        qs.stringify({
          userId: this.state.curSelData.userId,
          address: "new"
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }
    this.setState({ addressVisible: false });
  };

  setSalesmanScore = async () => {
    try {
      const result = await axios.post(
        "/channel/salesmanScore/add",
        qs.stringify({
          userId: this.state.curSelData.userId,
          inScore: this.state.salesmanInScore,
          outScore: this.state.salesmanOutScore
        })
      );
      if (result.code === 0) {
        message.success(result.msg);
      } else {
        message.error(result.msg);
      }
    } catch (e) {
      console.log(e);
      message.error(e.message || e.msg);
    }
    this.setState({ salesmanScoreVisible: false });
  };
  //翻页
  handlePageChange = (page, pageSize) => {
    this.setState(
      {
        curPage: page
      },
      this.searchTable
    );
  };

  onShowSizeChange = (current, pageSize) => {
    this.setState(
      {
        pageSize: pageSize,
        curPage: current
      },
      this.searchTable
    );
  };

  render() {
    const {
      initForm,
      formItmes,
      loading,
      tableData,
      curPage,
      pageSize
    } = this.state;
    const columns = [
      {
        title: "用户编号",
        dataIndex: "userId",
        key: "userId"
      },
      {
        title: "用户名称",
        dataIndex: "loginName",
        key: "loginName"
      },
      {
        title: "部门",
        dataIndex: "dept",
        key: "dept",
        render: (value, data) => <span>{data.dept.deptName}</span>
      },
      {
        title: "用户状态",
        dataIndex: "status",
        key: "status",
        render: (value, data) => {
          return (
            <Switch
              checked={value === "0"}
              onChange={() => this.handleUserStateChange(data)}
            />
          );
        }
      },
      {
        title: "创建时间",
        dataIndex: "createTime",
        key: "createTime"
      },
      {
        title: "操作",
        key: "action",
        render: (text, record) => (
          <div>
            {(record.roleId == 101 || record.roleId == 106) && (
              // 商户
              <>
                <Button
                  type="link"
                  size={"small"}
                  onClick={() =>
                    this.setState({ payVisible: true, curSelData: record })
                  }
                >
                  支付密码
                </Button>
              </>
            )}
            {record.roleId == 107 && (
              // 业务员
              <>
                <Button
                  type="link"
                  size={"small"}
                  onClick={async () => {
                    const result = await axios.get(
                      "/channel/salesmanInfo/getUser/" + record.userId
                    );
                    this.setState({
                      scoreVisible: true,
                      curSelData: record,
                      scoreValue: result.data.rate
                    });
                  }}
                >
                  汇率设置
                </Button>
                <Button
                  type="link"
                  size={"small"}
                  onClick={async () => {
                    const result = await axios.get(
                      "/channel/salesmanInfo/getUser/" + record.userId
                    );
                    this.setState({
                      addressVisible: true,
                      curSelData: record,
                      addressValue: result.data.address
                    });
                  }}
                >
                  钱包设置
                </Button>
                <Button
                  type="link"
                  size={"small"}
                  onClick={async () => {
                    this.setState({
                      salesmanScoreVisible: true,
                      curSelData: record,
                      salesmanInScore: 0,
                      salesmanOutScore: 0
                    });
                  }}
                >
                  加减分
                </Button>
              </>
            )}
            {record.roleId == 109 && (
              // 业务员
              <>
                <Button
                  type="link"
                  size={"small"}
                  onClick={async () => {
                    const result = await axios.get(
                      "/system/user/list/group/" + record.userId
                    );
                    this.setState({
                      visibleGroupDlg: true,
                      curSelData: record,
                      groupUserList: result.data
                    });
                  }}
                >
                  分配组员
                </Button>
              </>
            )}
            <Button
              type="link"
              size={"small"}
              onClick={() =>
                this.setState({ pwdVisible: true, curSelData: record })
              }
            >
              重置密码
            </Button>
            <Button
              type="danger"
              size={"small"}
              style={{ marginLeft: 10 }}
              onClick={() => this.delUser(record)}
            >
              删除
            </Button>
          </div>
        )
      }
    ];
    return (
      <div>
        <MyForm
          initForm={initForm}
          items={formItmes}
          handleSearch={this.handleSearch}
        />
        <div style={{ display: "flex", gap: "10px", marginBottom: "10px" }}>
          {/*<Button type="primary" onClick={this.addUser}>*/}
          {/*  添加会员*/}
          {/*</Button>*/}
          {this.props.isAdmin && (
            <>
              <Button type="primary" onClick={this.addGroup}>
                添加组长
              </Button>
              <Button type="primary" onClick={this.addAdmin}>
                添加管理员
              </Button>
            </>
          )}
          <Button type="primary" onClick={this.addSalesman}>
            添加业务员
          </Button>
        </div>
        <Spin spinning={loading}>
          {/*<div style={{marginBottom: 10}}>*/}
          {/*<Button onClick={this.addUser} type="primary">*/}
          {/*<Icon type="plus" />添加用户*/}
          {/*</Button>*/}
          {/*</div>*/}
          <Table
            dataSource={tableData.rows}
            columns={columns}
            pagination={false}
          />
          <Pagination
            style={{ marginTop: 10, marginBottom: 20 }}
            total={tableData.total}
            showTotal={total => `共 ${total} 项`}
            pageSizeOptions={["10", "20", "50", "100", "500"]}
            showSizeChanger
            onShowSizeChange={this.onShowSizeChange}
            pageSize={pageSize}
            current={curPage}
            onChange={this.handlePageChange}
          />
          <Modal
            title="设置业务员汇率"
            visible={this.state.scoreVisible}
            onOk={this.setRate}
            onCancel={() => this.setState({ scoreVisible: false })}
          >
            <div style={{ display: "flex", alignItems: "center" }}>
              <div>请输入汇率为：</div>
              <Input
                type={"number"}
                style={{ width: 200 }}
                value={this.state.scoreValue}
                onChange={value =>
                  this.setState({ scoreValue: value.target.value })
                }
              />
            </div>
          </Modal>
          <Modal
            title={"加减分" + this.state.curSelData.userName}
            visible={this.state.salesmanScoreVisible}
            onOk={this.setSalesmanScore}
            onCancel={() => this.setState({ salesmanScoreVisible: false })}
          >
            <div style={{ display: "flex", alignItems: "center" }}>
              <div>请输入入金数：</div>
              <Input
                type={"number"}
                defaultValue={0}
                style={{ width: 200 }}
                value={this.state.salesmanInScore}
                onChange={value =>
                  this.setState({ salesmanInScore: value.target.value })
                }
              />
            </div>
            <div
              style={{
                display: "flex",
                alignItems: "center",
                marginTop: "16px"
              }}
            >
              <div>请输入出金数：</div>
              <Input
                type={"number"}
                defaultValue={0}
                style={{ width: 200 }}
                value={this.state.salesmanOutScore}
                onChange={value =>
                  this.setState({ salesmanOutScore: value.target.value })
                }
              />
            </div>
          </Modal>
          <Modal
            title="设置钱包地址"
            visible={this.state.addressVisible}
            onOk={this.setAddress}
            okText={"更新钱包地址"}
            onCancel={() => this.setState({ addressVisible: false })}
          >
            <div style={{ display: "flex", alignItems: "center" }}>
              <div>钱包地址：</div>
              <Input
                disabled={true}
                style={{ width: 300 }}
                value={this.state.addressValue}
              />
            </div>
          </Modal>
          <Modal
            title="重置支付密码"
            visible={this.state.payVisible}
            onOk={this.updatePayPwd}
            onCancel={() => this.setState({ payVisible: false })}
          >
            <div style={{ display: "flex", alignItems: "center" }}>
              <div>请输入支付密码：</div>
              <Input
                style={{ width: 200 }}
                value={this.state.payValue}
                onChange={value =>
                  this.setState({ payValue: value.target.value })
                }
              />
            </div>
          </Modal>
          <Modal
            title="重置登录密码"
            visible={this.state.pwdVisible}
            onOk={this.updateUserPwd}
            onCancel={() => this.setState({ pwdVisible: false })}
          >
            <div style={{ display: "flex", alignItems: "center" }}>
              <div>请输入登录密码：</div>
              <Input
                style={{ width: 200 }}
                value={this.state.pwdValue}
                onChange={value =>
                  this.setState({ pwdValue: value.target.value })
                }
              />
            </div>
          </Modal>
          <AddUserForm
            visible={this.state.visibleDlg}
            initForm={this.state.initCardForm}
            title={this.state.cardFormTitle}
            cardFormType={this.state.cardFormType}
            okCb={() => {
              this.setState({ visibleDlg: false });
              this.init();
            }}
            cancelCb={() => this.setState({ visibleDlg: false })}
          />
          <EditGroupUser
            visible={this.state.visibleGroupDlg}
            groupUserList={this.state.groupUserList}
            userInfo={this.state.curSelData}
            cancelCb={() => this.setState({ visibleGroupDlg: false })}
          />
          <UserForm
            isAdmin={this.props.isAdmin}
            visible={this.state.userDlg}
            initForm={this.state.initCardForm}
            title={this.state.cardFormTitle}
            cardFormType={this.state.cardFormType}
            okCb={() => {
              this.setState({ userDlg: false });
              this.init();
            }}
            cancelCb={() => this.setState({ userDlg: false })}
          />
        </Spin>
      </div>
    );
  }
}

export default connect(
  mapStateToProps,
  mapDispatchToProps
)(withRouter(UserMng));
